package cn.demo.springcloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
public class LoginFilter extends ZuulFilter {

    /**
     * 过滤器类型
     * pre：可以在请求被路由之前调用
     * route：在路由请求时候被调用
     * post：在route和error过滤器之后被调用
     * error：处理请求时发生错误时被调用
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤器顺序 - 数字小的先执行
     */
    @Override
    public int filterOrder() {
        return 2;
    }

    /**
     * 过滤器是否生效 - 返回true需要过滤，false不需要过滤
     */
    @Override
    public boolean shouldFilter() {
        //共享RequestContext，上下文对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        System.out.println(request.getRequestURI());

        List<String> urls = new ArrayList<>();
        urls.add("/login".toLowerCase());
        if (urls.contains(request.getRequestURI().toLowerCase())) {
            return false;
        }

        return true;
    }

    /**
     * 过滤业务 - 只有上面返回true，才会进入该方法
     */
    @Override
    public Object run() throws ZuulException {
        //JWT
        boolean flag = false;
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        Cookie[] cookies = request.getCookies();
        String token = null;
        if(!Objects.isNull(cookies)){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    token = cookie.getValue();
                    break;
                }
            }
        }

        //校验token，校验通过则给flag赋值true
        flag = true;

        if (!flag) {
            //校验不通过
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }else {
            //校验通过 - 传递信息给微服务
            requestContext.addZuulRequestHeader("user", "lhc");
        }
        return null;
    }

}
